import {ImmerReducer,Effect} from "umi";
import {fetchProduct} from '@/api/index'
export interface stateType{
    productList:object[]|[];
    err:string|null
}
interface productModelType{
    namespace:string,
    state:stateType,
    reducers:{
        setProductList:ImmerReducer<stateType>//ImmerReducer用来方便的更新状态
    },
    effects:{
        getProductList:Effect
    }
}
interface callType{
    data:any
    call(api:any):any
}
const productModel:productModelType={
    namespace:'product',//命名空间
    state:{
        productList:[],
        err:null
    },
    reducers:{
        setProductList(state,action){
            state.productList=action.payload.data;
            state.err=action.payload.err
        }
    },
    effects:{//副作用，相当于vuex中的actions
        *getProductList({payload},{call,put}){
            //获取数据
            yield new Promise((resolve,reject)=>{
                setTimeout(()=>{
                    resolve(fetchProduct)
                },2000)
            })
            try{
               
                let res:callType=yield call(fetchProduct)
                yield put({type:"setProductList",payload:{data:res.data,err:null}})
            }catch(e:any){
                console.log(e)
                yield put({type:"setProductList",payload:{data:[],err:e.toString()}})
            }

        }
        
    }
}
export default productModel